#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Conexión 3G
# Copyright (C) 2009 Plan Ceibal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact information: comunidad@plan.ceibal.edu.uy
# Plan Ceibal http://www.ceibal.edu.uy
#
import pango
import gtk
import os, sys, subprocess, fcntl, select
import gobject
import SetConfiguracion
import gtk.glade
import InterfazGlade
import string
import logging

# Clase que controla la ventana de configuración de la actividad de Conexión

# Constantes de Configuración
PATH_CONFIG_DETECTED  =  '/home/local/.wvdial.conf.detect'


# Clase para el manejo de la ventana de las opciones de configuración
class InterfazGladeSetup:
	def __init__(self, interfazMainGlade, runaslib=True):
		self.interfazGlade = interfazMainGlade
		self.setupwindows = self.interfazGlade.xml.get_widget('setupwindows')
		
		self.interfazGlade.xml.signal_autoconnect(self)
		# Obtener Controles
		self.deviceTxt = self.interfazGlade.xml.get_widget('device')
		self.typeTxt = self.interfazGlade.xml.get_widget('type')
		self.dns1 = self.interfazGlade.xml.get_widget('Dns1')
		self.dns2 = self.interfazGlade.xml.get_widget('Dns2')
		self.manual_dns = self.interfazGlade.xml.get_widget('manual_dns')
 		self.auto_dns = self.interfazGlade.xml.get_widget('auto_dns')
 		self.InitString1 = self.interfazGlade.xml.get_widget('InitString1')
 		self.InitString2 = self.interfazGlade.xml.get_widget('InitString2')
 		self.InitString3 = self.interfazGlade.xml.get_widget('InitString3')


		# Se cargan los controles con la configuración Anterior
		self.deviceTxt.get_child().set_text(self.interfazGlade.config3G.Modem)

		if (self.interfazGlade.config3G.ModemType == "Analog Modem"):  
			self.typeTxt.set_active(0)
		if (self.interfazGlade.config3G.ModemType == "USB Modem"):  
			self.typeTxt.set_active(1)
		if (self.interfazGlade.config3G.ModemType == "ISDN Terminal Adapter"):  
			self.typeTxt.set_active(2)
		if (self.interfazGlade.config3G.ModemType not in ("Analog Modem","USB Modem","ISDN Terminal Adapter")):
			self.typeTxt.set_active(0)
		if (self.interfazGlade.config3G.AutoDns):
			self.auto_dns.set_active(1)
			self.dns1.set_sensitive(False)
			self.dns2.set_sensitive(False)
		else:
			self.manual_dns.set_active(1)
			self.dns1.set_text(self.interfazGlade.config3G.Dns1)
			self.dns2.set_text(self.interfazGlade.config3G.Dns2)
		self.InitString1.set_text(self.interfazGlade.config3G.InitString1)
		self.InitString2.set_text(self.interfazGlade.config3G.InitString2)
		self.InitString3.set_text(self.interfazGlade.config3G.InitString3)
		
		self._logger = logging.getLogger('Conexion3G-activity')
		self._logger.setLevel(logging.DEBUG)
		
###################### Handlers ##############################

	def on_quit(self, *args):
		pass

	def on_setup_close(self, *args):
		pass

	def on_manual_dns(self, *args):
		if (self.manual_dns.get_active()):	
			self.dns1.set_sensitive(True)
			self.dns2.set_sensitive(True)

	def on_auto_dns(self, *args):
		if (self.auto_dns.get_active()):
			self.dns1.set_sensitive(False)
			self.dns2.set_sensitive(False)
			self.dns1.set_text("")
			self.dns2.set_text("")

	def on_detect(self, *args):
		# Start Proceso
		try:
			command=[ InterfazGlade.PATH_WVDIAL, 'detectmodem',PATH_CONFIG_DETECTED]
			proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			task = self.on_detect_check_progress(proc)
			gobject.idle_add(task.next)
		except OSError, e:
			self.printMensaje("Error ejecutando wvdial-wrapper. Fallo en la ejecución:" + str(e))
		# Fin Proceso		

	def on_detect_check_progress(self, proc):
		returncode = proc.poll()
		i = 0
		returnstring = ""
		# Archivos para comunicacion con los procesos
		try:
			outfile=proc.stdout
			outfd=outfile.fileno()
			file_flags = fcntl.fcntl(outfd, fcntl.F_GETFL)
			fcntl.fcntl(outfd, fcntl.F_SETFL, file_flags | os.O_NDELAY)

			outfileerr=proc.stderr
			outfderr= outfileerr.fileno()
			file_flags = fcntl.fcntl(outfderr, fcntl.F_GETFL)
			fcntl.fcntl(outfderr, fcntl.F_SETFL, file_flags | os.O_NDELAY)

		except (OSError, IOError), e:
			self.printMensaje("Error corriendo el script 'wvdialconf' : fallo en la comunicación con el proceso: " + str(e))

		conexion = False
		modemdetectado = False
		# Mientras no termine el proceso 
		while (returncode == None): 
			# Chequeo Proceso
			returncode = proc.poll()

			ready = select.select([outfd],[],[], 0.2) # wait for input
			if outfd in ready[0]:
				outchunk = outfile.read()
				if outchunk <> "":
					self._logger.debug("Salida Terminal StdOut:||||||||||||||||||||||\n" + outchunk + "\n||||||||||||||||||||||\n")
					returnstring = outchunk
					if (string.find(outchunk, "Found a modem on")<>-1):
						modemdetectado = True
			ready = select.select([outfderr],[],[],0.2) # wait for error
			if outfderr in ready[0]:
				outchunk = outfileerr.read()
				if (outchunk <> ""):
					self._logger.debug("Salida Terminal StdError:||||||||||||||||||||||\n" + outchunk + "\n||||||||||||||||||||||\n")
					returnstring = outchunk
			yield True

		self._logger.debug("Salida del proceso wvdialconf: " + str(returncode) + " - String Salida: " + returnstring)

		if (modemdetectado):
			self.interfazGlade.printMensaje("Modem Detectado")
			
		else:
			self.interfazGlade.printMensaje("No se detecto ningun modem")
		
		if (modemdetectado):
			configdetect3G = self.getModem3GConfiguracionDetectada()
			# Se cargan los controles con la configuración Anterior
			self.deviceTxt.get_child().set_text(configdetect3G.Modem)

			if (configdetect3G.ModemType == "Analog Modem"):  
				self.typeTxt.set_active(0)
			if (configdetect3G.ModemType == "USB Modem"):  
				self.typeTxt.set_active(1)
			if (configdetect3G.ModemType == "ISDN Terminal Adapter"):  
				self.typeTxt.set_active(2)
			if (configdetect3G.ModemType not in ("Analog Modem","USB Modem","ISDN Terminal Adapter")):
				self.typeTxt.set_active(0)

			self.InitString1.set_text(configdetect3G.InitString1)
			self.InitString2.set_text(configdetect3G.InitString2)
			self.InitString3.set_text(configdetect3G.InitString3)
		yield False	

	
	def getModem3GConfiguracionDetectada(self):
		# Leer archivo de Configuracion Detectada por wvdialconf
		config3G = SetConfiguracion.Conexion3GConfiguracion()
		try:
			if os.path.exists(PATH_CONFIG_DETECTED):
				lines = open(PATH_CONFIG_DETECTED, 'r') 
				for line in lines:	
					if line.startswith('Modem ='):
						config3G.Modem = SetConfiguracion.lineSplitSignoIgual(line, 'Modem = ')
						continue
					if line.startswith('Modem Type ='):
						config3G.ModemType = SetConfiguracion.lineSplitSignoIgual(line, 'Modem Type =') 
						continue
					if line.startswith('Baud ='):
						# Se ignora
						continue
					if line.startswith('Init1 ='):
						config3G.InitString1 = SetConfiguracion.lineSplitSignoIgual(line, 'Init1 =') 
						continue
					if line.startswith('Init2 ='):
						config3G.InitString2 = SetConfiguracion.lineSplitSignoIgual(line, 'Init2 =') 
						continue
					if line.startswith('Init3 ='):
						config3G.InitString3 = SetConfiguracion.lineSplitSignoIgual(line, 'Init3 =') 
						continue
		except Exception, e:	
			self._logger.debug("Error leyendo el archivo de configuración")
			raise e
		return config3G


